import 'dart:core';

class DateUtils {
  
  static DateTime getFirstDayOfMonth(DateTime date) {
    return DateTime(date.year, date.month, 1);
  }

  
  static DateTime getLastDayOfMonth(DateTime date) {
    final nextMonth = DateTime(date.year, date.month + 1, 1);
    return nextMonth.subtract(const Duration(days: 1));
  }

  
  static int getWeekdayIndex(DateTime date) {
    return date.weekday % 7;
  }

  
  static int getDaysInMonth(DateTime date) {
    return getLastDayOfMonth(date).day;
  }

  
  static bool isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year && 
           date1.month == date2.month && 
           date1.day == date2.day;
  }

  
  static List<DateTime> getCalendarDays(DateTime monthDate) {
    final firstDay = getFirstDayOfMonth(monthDate);
    final lastDay = getLastDayOfMonth(monthDate);
    
    
    final startWeekday = getWeekdayIndex(firstDay);
    final daysInPreviousMonth = getDaysInMonth(DateTime(firstDay.year, firstDay.month - 1));
    
    
    final endWeekday = getWeekdayIndex(lastDay);
    final remainingDays = 6 - endWeekday;
    
    final calendarDays = <DateTime>[];
    
    
    for (int i = startWeekday - 1; i >= 0; i--) {
      final day = daysInPreviousMonth - i;
      calendarDays.add(DateTime(firstDay.year, firstDay.month - 1, day));
    }
    
    
    for (int i = 1; i <= lastDay.day; i++) {
      calendarDays.add(DateTime(monthDate.year, monthDate.month, i));
    }
    
    
    for (int i = 1; i <= remainingDays; i++) {
      calendarDays.add(DateTime(lastDay.year, lastDay.month + 1, i));
    }
    
    return calendarDays;
  }

  
  static String formatDate(DateTime date, {String format = 'yyyy-MM-dd'}) {
    final year = date.year.toString();
    final month = date.month.toString().padLeft(2, '0');
    final day = date.day.toString().padLeft(2, '0');
    
    return format
        .replaceAll('yyyy', year)
        .replaceAll('MM', month)
        .replaceAll('dd', day);
  }

  
  static String getMonthDisplayText(DateTime date) {
    return '${date.year}年${date.month}月';
  }
}